//
//  OpenDetailViewController.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/1.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//

#import "OpenDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "MoviePlayerViewController.h"
#import "PicAndTextBT.h"
#import "MBProgressHUD.h"
#import "UMSocial.h"
#import "UMSocialShakeService.h"
#import "UMSocialScreenShoter.h"
#import "DBTool.h"
@interface OpenDetailViewController ()<MoviePlayerViewControllerDataSource,UMSocialUIDelegate,UMSocialShakeDelegate>
@property (strong, nonatomic) UIImageView *iconImageView;
@property (strong,nonatomic) UIImageView *playImageView;
@property (strong,nonatomic) UIImageView *coverBlurred;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *cgAndDurLabel;
@property (strong, nonatomic) UILabel *descLabel;
@property (strong, nonatomic) PicAndTextBT *collectionBT;
@property (strong, nonatomic) UIButton *shareBT;
@property (strong, nonatomic) UIButton *downloadBT;

@property (strong,nonatomic) MBProgressHUD *progressHUD;//刷新视图
@property (strong,nonatomic) NSTimer *timer;//定时器让图片循环动态

//缓存
@property (strong,nonatomic) NSMutableData *data;
@property (strong,nonatomic) NSMutableArray *dataArray;
@property (assign,nonatomic) long long totalLenght;
@property (strong,nonatomic) NSMutableURLRequest *request;
@property (strong,nonatomic) NSString *cachePath;
@property (strong,nonatomic) NSString *fileName;
@property (strong,nonatomic) NSFileHandle *handle;

@end

@implementation OpenDetailViewController

- (void)viewDidDisappear:(BOOL)animated{
    //将图片frame重置
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 44, kScreenW, kScreenH * 0.4)];
}

- (void)runLoop{
    [UIView animateWithDuration:5 animations:^{
        _iconImageView.frame = CGRectMake(-20, -20 * kScreenH * 0.4/kScreenW, kScreenW + 20, kScreenH*0.4 + 20 * kScreenH * 0.4/kScreenW);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:5 animations:^{
            _iconImageView.frame = CGRectMake(0, 0, kScreenW, kScreenH * 0.4);
        } completion:nil];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH * 0.4)];
    _timer = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(runLoop) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [_timer fire];
    [self.view addSubview:_iconImageView];
    
    _playImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenW - 50) / 2, (kScreenH * 0.4 - 64) / 2, 50, 50)];
    _playImageView.image = [UIImage imageNamed:@"iconfont-bofang"];
    [self.view addSubview:_playImageView];
    
    _coverBlurred = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenH *0.4, kScreenW, kScreenH * 0.6 - 64)];
    [_coverBlurred setUserInteractionEnabled:YES];
    _coverBlurred.image = [UIImage imageNamed:@"wxl1"];
    [self.view addSubview:_coverBlurred];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, kScreenW - 16,40)];
    _titleLabel.textColor = [UIColor whiteColor];
    [_coverBlurred addSubview:_titleLabel];
    
    UIView *splitView = [[UIView alloc] initWithFrame:CGRectMake(8, 50, 200, 1)];
    splitView.backgroundColor = [UIColor whiteColor];
    [_coverBlurred addSubview:splitView];
    
    _cgAndDurLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 55, kScreenW - 16, 20)];
    _cgAndDurLabel.textColor = [UIColor whiteColor];
    [_coverBlurred addSubview:_cgAndDurLabel];
    
    CGFloat descLabelH = [self heightForString:_openEyesModel.desc];
    _descLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,80, kScreenW - 48,descLabelH)];
    _descLabel.textColor = [UIColor whiteColor];
    _descLabel.numberOfLines = 0;
    [_coverBlurred addSubview:_descLabel];
    
    _collectionBT = [[PicAndTextBT alloc] initWithFrame:CGRectMake(10,_coverBlurred.frame.size.height - 48, 80, 40)];
    [_collectionBT setImage:[UIImage imageNamed:@"iconfont-shoucang-2"] forState:UIControlStateNormal];
    [_collectionBT setTitle:@"收藏" forState:UIControlStateNormal];
    [_coverBlurred addSubview:_collectionBT];
    
    _shareBT = [[PicAndTextBT alloc] initWithFrame:CGRectMake(100,_coverBlurred.frame.size.height - 48, 80, 40)];
    [_shareBT setImage:[UIImage imageNamed:@"iconfont-share-2"] forState:UIControlStateNormal];
    [_shareBT setTitle:@"摇一摇" forState:UIControlStateNormal];
    [_coverBlurred addSubview:_shareBT];
    
    _downloadBT = [[PicAndTextBT alloc] initWithFrame:CGRectMake(200,_coverBlurred.frame.size.height - 48, 80, 40)];
    [_downloadBT setImage:[UIImage imageNamed:@"iconfont-xiazai"] forState:UIControlStateNormal];
    [_downloadBT addTarget:self action:@selector(downloadBT:) forControlEvents:UIControlEventTouchUpInside];
    //缓存文件名
    _fileName = [NSString stringWithFormat:@"%@.mp4",_openEyesModel.title];
    if ([[DBTool readPathTitle:_fileName] isEqualToString:@""]) {
        [_downloadBT setTitle:@"缓存" forState:UIControlStateNormal];
    }else{
        NSLog(@"[DBTool readPathTitle:_fileName] == %@",[DBTool readPathTitle:_fileName]);
        _downloadBT.userInteractionEnabled = NO;
        [_downloadBT setTitle:@"已缓存" forState:UIControlStateNormal];
    }
    [_coverBlurred addSubview:_downloadBT];
    
    //1.控件赋值
    [_iconImageView sd_setImageWithURL:[NSURL URLWithString:_openEyesModel.coverForDetail]];
    _titleLabel.text = _openEyesModel.title;
    _cgAndDurLabel.text = [NSString stringWithFormat:@"#%@ / %02d:%02d",_openEyesModel.category,_openEyesModel.duration / 60,_openEyesModel.duration % 60];
    _descLabel.text = _openEyesModel.desc;
    
    
    //给iconImageView添加一个手势,点击播放视频
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleRecognizer:)];
    [_playImageView setUserInteractionEnabled:YES];
    [_playImageView addGestureRecognizer:recognizer];
    
    NSString *shareText = [NSString stringWithFormat:@"视界可以带给你视觉,听觉的完美享受,不信你试试.http://user.qzone.qq.com/1091003414?ptlang=2052,%@你要分享的文字:",_openEyesModel.desc];
    [UMSocialShakeService setShakeToShareWithTypes:@[UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline]
                                         shareText:shareText
                                      screenShoter:nil
                                  inViewController:self
    
                                          delegate:self];
    
}
#pragma mark - 点击缓存按钮
- (void)downloadBT:(UIButton *)button{
    //1.设置网络请求
    NSString *str = _openEyesModel.playUrl;
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //2.发送请求
    NSString *componentStr = [NSString stringWithFormat:@"%@",_fileName];
    [NSURLConnection connectionWithRequest:request delegate:self];
    _cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:componentStr];
    NSLog(@"path ======== %@",_cachePath);
    
    [[NSFileManager defaultManager] createFileAtPath:_cachePath contents:nil attributes:nil];
    _handle = [NSFileHandle fileHandleForWritingAtPath:_cachePath];
}
//接受请求
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"%@",response);
    //获取数据的总长度
    _totalLenght = [response expectedContentLength];
    NSLog(@"%lld",_totalLenght);
    _data = [NSMutableData data];
}
//接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"-------%ld",(unsigned long)[_data length]);
    [_data appendData:data];
    NSLog(@"-------%.2f%%",100*(float)[_data length]/_totalLenght);
    NSString *downSpeed = [NSString stringWithFormat:@"%0.1f%%",100*(float)[_data length]/_totalLenght];
    [_downloadBT setTitle:downSpeed forState:UIControlStateNormal];
    
}
//接收数据完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"播放.......");
    if (_totalLenght == _data.length) {
        [_handle writeData:_data];
        //存取路径
        [DBTool savePath:_cachePath title:_fileName];
        
        //下载成功,提示用户
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"缓存成功,请播放..." preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        //下载成功,避免用户在此点击下载按钮,关闭下载按钮交互
        _downloadBT.userInteractionEnabled = NO;
        [_downloadBT setTitle:@"已缓存" forState:UIControlStateNormal];
    }else{
        //下载失败,提示用户
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"缓存失败..." preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }
    
}

//加载失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"失败");
}
#pragma mark - 计算字符串文本高度
- (CGFloat)heightForString:(NSString *)str{
    //文本的高度
    NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
    
    CGRect rect = [str boundingRectWithSize:CGSizeMake(210,1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

#pragma mark - 手势处理
- (void)handleRecognizer:(UITapGestureRecognizer *)recognizer{
    //进入播放器,关闭定时器
    [_timer invalidate];
    //1.当点击播放时,显示刷新
    _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_progressHUD];
    [_progressHUD show:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //2.移除刷新视图
        [_progressHUD hide:YES];//1.处理手势,播放视频
        //3.加载播放器
        [self playNetMovie];
        //4.移除手势
        [self.view removeGestureRecognizer:recognizer];
    });
}

#pragma mark - 推出播放器

- (void)playNetMovie{
    NSString *path = [DBTool readPathTitle:_fileName];
    if (![path isEqualToString:@""]) {//缓存中有播放资源,播放本地缓存视频
        NSLog(@"缓存中有播放资源,播放本地缓存视频");
        NSURL *url = [NSURL fileURLWithPath:path];
        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initLocalMoviePlayerViewControllerWithURL:url movieTitle:_openEyesModel.title];
        [self presentViewController:movieVC animated:YES completion:nil];
    } else {//没有缓存,根据playerurl播放网络视频
        NSLog(@"没有缓存,根据playerurl播放网络视频");
        NSURL *url = [NSURL URLWithString:_openEyesModel.playUrl];
        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initNetworkMoviePlayerViewControllerWithURL:url movieTitle:_openEyesModel.title];
        movieVC.datasource = self;
        [self presentViewController:movieVC animated:YES completion:nil];
    }
    
    [self onActionDissmissPlayer];//进入播放器解除摇一摇监控
}

#pragma mark - 播放器代理方法
- (NSDictionary *)previousMovieURLAndTitleToTheCurrentMovie{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSURL URLWithString:@"http://v.youku.com/player/getRealM3U8/vid/XNjQ5MDM3Nzg0/type/mp4/v.m3u8"],KURLOfMovieDicTionary,@"qqqqqqq",KTitleOfMovieDictionary, nil];
    return dic;
}
- (NSDictionary *)nextMovieURLAndTitleToTheCurrentMovie{
    return nil;
}
- (BOOL)isHavePreviousMovie{
    return NO;
}
- (BOOL)isHaveNextMovie{
    return NO;
}
#pragma mark - 横屏
- (BOOL)shouldAutorotate{
    return YES;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}

#pragma mark - 摇一摇分享
- (void)shareBT:(UIButton *)button{
    //点击了摇一摇按钮,主动触发摇一摇动作
    
}

-(UMSocialShakeConfig)didShakeWithShakeConfig{
    //摇一摇动作的回调方法
    //相应摇一摇后，你分享自己的播放器得到截图
    UIImage *image = [[UMSocialScreenShoterDefault screenShoter] getScreenShot];
    [UMSocialShakeService setScreenShotImage:image];
    
    return UMSocialShakeConfigDefault;
}

-(void)didCloseShakeView{
    //用户分享或者关闭分享页面的回调方法

}

-(void)didFinishShareInShakeView:(UMSocialResponseEntity *)response{
    //分享完成的回调方法
    if (response.responseCode == UMSResponseCodeSuccess) {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alertView show];
    } else if(response.responseCode != UMSResponseCodeCancel) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"失败" message:@"分享失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        }
    }
}

-(void)onActionDissmissPlayer{
    //当退出详情界面时解除监听摇一摇事件
    [UMSocialShakeService unShakeToSns];
}
@end
